import 'package:xrenovation/utils/http.dart';
import 'package:xrenovation/utils/storage.dart';

class AuthApi {
  static Future<List<Map<String, dynamic>>> getCountries() async {
    final response = await Http.get('/region/list');
    if (response.data['code'] == 200) {
      return (response.data['data'] as List)
          .where((item) => item['type'] == 'COUNTRY')
          .cast<Map<String, dynamic>>()
          .toList();
    }
    throw Exception('Failed to load countries');
  }

  static Future<List<Map<String, dynamic>>> getStates(String countryCode) async {
    final response = await Http.get('/region/list?parentId=$countryCode');
    if (response.data['code'] == 200) {
      return (response.data['data'] as List)
          .where((item) => item['type'] == 'STATE_PROVINCE')
          .cast<Map<String, dynamic>>()
          .toList();
    }
    throw Exception('Failed to load states');
  }

  static Future<Map<String, dynamic>> login({
    required String email,
    required String password,
    bool rememberMe = false,
  }) async {
    final res = await Http.post('/user/login', {'email': email, 'password': password, 'rememberMe': rememberMe});
    return res.data;
  }

  static Future<Map<String, dynamic>> logout() async {
    final res = await Http.post('/user/logout', {});
    await Storage.remove('user_info');
    await Storage.clearToken();
    return res.data;
  }

  static Future<Map<String, dynamic>> register({
    required String email,
    required String password,
    required String username,
    required String phone,
    required String city,
    required String state,
    required String country,
    required String code,
  }) async {
    final res = await Http.post('/user/register', {
      'email': email,
      'password': password,
      'username': username,
      'phone': phone,
      'city': city,
      'state': state,
      'country': country,
      'code': code,
    });
    return res.data;
  }

  static Future<Map<String, dynamic>> resetPassword({
    required String email,
    required String code,
    required String password,
  }) async {
    final res = await Http.post('/user/modifyPassword', {'email': email, 'code': code, 'password': password});
    return res.data;
  }

  static Future<Map<String, dynamic>> sendRegisterCode(String email) async {
    final res = await Http.post('/email/sendCode', {'email': email, 'emailCodeType': 'REGISTER'});
    return res.data;
  }

  static Future<Map<String, dynamic>> sendResetPasswordCode(String email) async {
    final res = await Http.post('/email/sendCode', {'email': email, 'emailCodeType': 'RESET_PASSWORD'});
    return res.data;
  }
}
